package com.jp.knowledge.my.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.LinearLayout;

import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.comm.SlidingActivity;
import com.jp.knowledge.adapter.FragMentAdapter;
import com.jp.knowledge.model.UserData;
import com.jp.knowledge.my.fragment.InviteMemberFragment;
import com.jp.knowledge.my.model.OrganizaModel;
import com.jp.knowledge.view.TabView;

import org.xutils.view.annotation.ViewInject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 528787067@qq.com on 2017/4/14.
 */

public class InviteMemberActivity extends SlidingActivity {

    private static final int REQUEST_CONTACTS_PREMISSION = 0x01;

    @ViewInject(R.id.view_page)
    private ViewPager viewPager;
    @ViewInject(R.id.tab_view)
    private TabView tabView;
    private View notPremissionView;

    private List<String> tabNames;
    private List<Fragment> fragments;
    private FragMentAdapter adapter;

    @Override
    protected int getResourceId() {
        return R.layout.activity_company_base;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CONTACTS_PREMISSION && grantResults.length > 0){
            if(grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                initViewPager();
            } else{
                notPremissionView.setVisibility(View.VISIBLE);
                tabView.setVisibility(View.GONE);
                viewPager.setVisibility(View.GONE);
                ToasUtil.toast(this, "抱歉，你没有权限访问手机通讯录");
            }
        }
    }

    @Override
    protected void init() {
        UserData userData = application.getUserData();
        if (userData == null) {
            ToasUtil.toast(mContext, "请先登录!");
            finish();
            return;
        }
        List<OrganizaModel> companyList = userData.getCompanyList();
        if (companyList == null || companyList.size() == 0) {
            ToasUtil.toast(mContext, "尚未加入任何组织!");
            finish();
            return;
        }

        notPremissionView = View.inflate(this, R.layout.colleague_contacts_bg, null);
        notPremissionView.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        ((ViewGroup)contentView).addView(notPremissionView);
        notPremissionView.setVisibility(View.GONE);
        tabView.setVisibility(View.GONE);
        viewPager.setVisibility(View.GONE);

        tabNames = new ArrayList<>();
        fragments = new ArrayList<>();
        initTitle();

        notPremissionView.setVisibility(View.VISIBLE);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.READ_CONTACTS},
                    REQUEST_CONTACTS_PREMISSION);
            return;
        }

        initViewPager();
        scrollToCompany(getIntent().getStringExtra("companyId"));
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        scrollToCompany(intent.getStringExtra("companyId"));
    }

    private void scrollToCompany(String companyId){
        if(companyId == null || fragments == null || fragments.size() <= 1)
            return;
        for(int i = 0, j = fragments.size(); i < j; i++){
            if(companyId.equals(((InviteMemberFragment)fragments.get(i)).getCompanyId())){
                viewPager.setCurrentItem(i);
                break;
            }
        }
    }

    private void initTitle() {
        topName.setText("邀请成员");
        rightIcon.setVisibility(View.GONE);
        leftIcon.setImageResource(R.mipmap.guanzhufanhui);
        leftIcon.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void initViewPager(){
        notPremissionView.setVisibility(View.GONE);
        viewPager.setVisibility(View.VISIBLE);
        tabView.setVisibility(View.VISIBLE);

        List<OrganizaModel> companyList = application.getUserData().getCompanyList();
        for(OrganizaModel organizaModel : companyList)
            fragments.add(InviteMemberFragment.newInstance(organizaModel));
        tabNames.clear();
        for(OrganizaModel organizaModel : companyList)
            tabNames.add(organizaModel.getCompanyName());
        adapter = new FragMentAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        tabView.setupWithViewPager(viewPager);
        tabView.setTabItems(tabNames);
        if(tabNames.size() <= 1)
            tabView.setVisibility(View.GONE);
        else
            tabView.setVisibility(View.VISIBLE);
    }

    @Override
    public void finish() {
        InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm.isActive() && this.getCurrentFocus() != null)
            if (this.getCurrentFocus().getWindowToken() != null)
                imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        super.finish();
    }
}
